import configparser
import logging
import os
import sys
from typing import List

from PyQt5 import QtWidgets
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QWidget, QFileDialog, QTableWidgetItem, QMessageBox, QTableWidget

from data.defines import *
from data.gisutils import calc_ref_lonlat
from gcs_views.ui_airport_setting import Ui_AirportsSetPad


def _route_read_file(table_route: QTableWidget):
    filename, filetype = QFileDialog.getOpenFileName(None,
                                                     "选取文件",
                                                     os.getcwd(),
                                                     "CSV Files (*.taxi.csv)")
    if len(filename) == 0:
        return

    try:
        # 读取文件
        with open(filename, 'r') as fr:
            data_arr = fr.read().strip().split('\n')
            fr.close()
            # print(data_arr)
            del data_arr[0]
            table_len = table_route.rowCount()
            for i in range(table_len):
                table_route.removeRow(0)

            table_route.setRowCount(len(data_arr))
            for idx, line in enumerate(data_arr):
                route_item = line.split(',')
                if len(route_item) != 4:
                    logging.error("错误的航线格式")
                    return
                str_dot = route_item[0]
                str_lon = route_item[1]
                str_lat = route_item[2]
                str_radious = route_item[3]

                table_route.setItem(idx, 0, QTableWidgetItem(str_dot))
                table_route.setItem(idx, 1, QTableWidgetItem(str_lon))
                table_route.setItem(idx, 2, QTableWidgetItem(str_lat))
                table_route.setItem(idx, 3, QTableWidgetItem(str_radious))
    except Exception as e:
        logging.error(repr(e))
        QMessageBox.information(None, "警告", "航线文件加载失败！" + repr(e),
                                QMessageBox.Yes, QMessageBox.Yes)


def _route_save2file(table_route: QTableWidget):
    filename, filetype = QFileDialog.getSaveFileName(None, 'save file', os.getcwd(), "CSV Files (*.taxi.csv)")
    if len(filename) == 0:
        return

    route_str = "Dot,Lon,Lat,Radious\n"
    total = table_route.rowCount()
    for i in range(total):
        s = table_route.item(i, 0).text().strip()
        s += ',' + table_route.item(i, 1).text().strip()
        s += ',' + table_route.item(i, 2).text().strip()
        s += ',' + table_route.item(i, 3).text().strip()
        route_str += s + '\n'
    try:
        with open(filename, 'w') as f:
            f.write(route_str)
            f.close()
    except Exception as e:
        QMessageBox.information(None, 'info', '导出写入失败！' + repr(e), QMessageBox.Ok)


def _table_add_dot(table_route: QTableWidget):
    idx = table_route.currentRow()
    total = table_route.rowCount()
    if idx == -1:
        table_route.setRowCount(total + 1)
    else:
        table_route.insertRow(idx + 1)


def _table_del_dot(table_route: QTableWidget):
    idx = table_route.currentRow()
    if idx != -1:
        table_route.removeRow(idx)


def _table_clear(table_route: QTableWidget):
    table_len = table_route.rowCount()
    for i in range(table_len):
        table_route.removeRow(0)


def _check_and_get_taxi_route(table_route: QTableWidget):
    row = table_route.rowCount()
    route_list = []
    if row == 0:
        QMessageBox.information(None, 'info', '请先添加航路点', QMessageBox.Ok)
        return route_list, row
    for i in range(row):
        p = RouteInfo()
        for j in range(4):
            item = table_route.item(i, j)
            if item is None:
                QMessageBox.information(None, 'info', '数据不完整！', QMessageBox.Ok)
                return [], 0
            else:
                value_str = item.text().strip()
                if len(value_str) == 0:
                    QMessageBox.information(None, 'info', '数据不完整！', QMessageBox.Ok)
                    return [], 0
        try:
            p.no = i + 1
            p.lon = float(table_route.item(i, 1).text().strip())
            p.lat = float(table_route.item(i, 2).text().strip())
            p.radious = int(table_route.item(i, 3).text().strip())
            route_list.append(p)
        except ValueError as e:
            QMessageBox.information(None, 'info', '第 %d 行 数据格式错误！' % p.no, QMessageBox.Ok)
            logging.error(repr(e))
            return route_list, i
    return route_list, row


def _table_load_taxi_route(table_route: QTableWidget, route_list: List[RouteInfo]):
    table_len = table_route.rowCount()
    dot_num = len(route_list)
    for i in range(table_len):
        table_route.removeRow(0)
    if dot_num == 0:
        return
    table_route.setRowCount(dot_num)
    for idx in range(dot_num):
        str_dot = str(route_list[idx].no)
        str_lon = str(route_list[idx].lon)
        str_lat = str(route_list[idx].lat)
        str_radious = str(route_list[idx].radious)
        table_route.setItem(idx, 0, QTableWidgetItem(str_dot))
        table_route.setItem(idx, 1, QTableWidgetItem(str_lon))
        table_route.setItem(idx, 2, QTableWidgetItem(str_lat))
        table_route.setItem(idx, 3, QTableWidgetItem(str_radious))


class AirportSetPad(QWidget, Ui_AirportsSetPad):
    rwy_sig_show_to_map = pyqtSignal(object)  # 使用字典传递跑道数据 {start_lon,start_lat,end_lon,end_lat,width}
    rwy2_sig_show_to_map = pyqtSignal(object)  # 使用字典传递跑道数据 {start_lon,start_lat,end_lon,end_lat,width}
    rwy_sig_upload_takeoff_rwy = pyqtSignal(object)  # 使用字典传递数据 {idx,lon,lat,alt,psi,len}
    rwy_sig_upload_landing_rwy = pyqtSignal(object)  # 使用字典传递数据 {idx,lon,lat,alt,psi,len}
    rwy_sig_get_rwy = pyqtSignal()  # 触发后调用发送命令接口发送遥控指令
    rwy_sig_delete_rwy = pyqtSignal()  # 触发后调用发送命令接口发送遥控指令

    rwy_sig_get_config_result = pyqtSignal(object)  # 使用字典传入跑道数据 takeoff_rwy/landing_rwy {idx,lon,lat,alt,psi,len}
    rwy_sig_get_delete_result = pyqtSignal()  # 删除成功后触发此信号

    taxiin_sig_upload_start = pyqtSignal(list, int)  # 驶入航线装订信号，本地发出，外部接收
    taxiout_sig_upload_start = pyqtSignal(list, int)  # 驶出航线装订信号，本地发出，外部接收
    taxi_route_sig_show2map = pyqtSignal(list)  # 将航线显示到地图 本地发出，外部接收
    taxiin_sig_get_config = pyqtSignal()  # 查询驶入航线信号，本地发出，外部接收
    taxiout_sig_get_config = pyqtSignal()  # 查询驶出航线信号，本地发出，外部接收
    taxiin_sig_get_result = pyqtSignal(list)  # 驶入航线查询完成信号，外部发出，本地接收
    taxiout_sig_get_result = pyqtSignal(list)  # 驶出航线查询完成信号，外部发出，本地接收

    taxiin_route_sig_download_finished = pyqtSignal(list)
    taxiin_route_sig_load_from_map = pyqtSignal()

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.gui_init()

    def gui_init(self):
        # self.tableWidget.setColumnWidth(0, 40) # 根据需要调整列宽
        # self.tableWidget.setColumnWidth(1, 200)
        # self.tableWidget.setColumnWidth(2, 200)
        # self.tab_input.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.rwy_btn_read_config.clicked.connect(self.rwy_read_cfg)
        self.rwy_btn_save_config.clicked.connect(self.rwy_save_cfg)

        self.rwy_btn_upload_landing_rwy.clicked.connect(self.rwy_upload_landing)
        self.rwy_btn_upload_takeoff_rwy.clicked.connect(self.rwy_upload_takeoff)
        self.rwy_btn_show_rwy_to_map.clicked.connect(self.rwy_show2map)
        self.rwy_btn_clear_input.clicked.connect(self.rwy_clear_input)

        self.rwy_btn_get_rwy.clicked.connect(self.rwy_get_config)
        self.rwy_sig_get_config_result.connect(self.rwy_update_result)
        self.rwy_sig_get_delete_result.connect(self.rwy_clear_result)
        self.rwy_btn_delete_rwy.clicked.connect(self.rwy_delete_config)
        self.rwy_btn_show_rwy_to_map2.clicked.connect(self.rwy_show_config2map)
        self.rwy_btn_clear_result.clicked.connect(self.rwy_clear_result)
        self.rwy_btn_save_result.clicked.connect(self.rwy_save_result)

        self.taxiin_btn_read_file.clicked.connect(lambda: _route_read_file(self.taxiin_tab_editing))
        self.taxiin_btn_save2file.clicked.connect(lambda: _route_save2file(self.taxiin_tab_editing))
        self.taxiin_btn_add_dot.clicked.connect(lambda: _table_add_dot(self.taxiin_tab_editing))
        self.taxiin_btn_del_dot.clicked.connect(lambda: _table_del_dot(self.taxiin_tab_editing))
        self.taxiin_btn_upload.clicked.connect(self.taxiin_upload)
        self.taxiin_btn_clear_Input.clicked.connect(lambda: _table_clear(self.taxiin_tab_editing))
        self.taxiin_btn_show2map.clicked.connect(lambda: self.show_taxi_route2map(self.taxiin_tab_editing))
        self.taxiin_btn_get.clicked.connect(lambda: self.taxiin_sig_get_config.emit())
        self.taxiin_btn_show2map2.clicked.connect(lambda: self.show_taxi_route2map(self.taxiin_tab_result))
        self.taxiin_btn_clear_result.clicked.connect(lambda: _table_clear(self.taxiin_tab_result))
        self.taxiin_btn_save_result.clicked.connect(lambda: _route_save2file(self.taxiin_tab_result))
        self.taxiin_sig_get_result.connect(lambda data: _table_load_taxi_route(self.taxiin_tab_result, data))

        self.taxiout_btn_read_file.clicked.connect(lambda: _route_read_file(self.taxiout_tab_editing))
        self.taxiout_btn_save2file.clicked.connect(lambda: _route_save2file(self.taxiout_tab_editing))
        self.taxiout_btn_add_dot.clicked.connect(lambda: _table_add_dot(self.taxiout_tab_editing))
        self.taxiout_btn_del_dot.clicked.connect(lambda: _table_del_dot(self.taxiout_tab_editing))
        self.taxiout_btn_upload.clicked.connect(self.taxiout_upload)
        self.taxiout_btn_clear_Input.clicked.connect(lambda: _table_clear(self.taxiout_tab_editing))
        self.taxiout_btn_show2map.clicked.connect(lambda: self.show_taxi_route2map(self.taxiout_tab_editing))
        self.taxiout_btn_get.clicked.connect(lambda: self.taxiout_sig_get_config.emit())
        self.taxiout_btn_show2map2.clicked.connect(lambda: self.show_taxi_route2map(self.taxiout_tab_result))
        self.taxiout_btn_clear_result.clicked.connect(lambda: _table_clear(self.taxiout_tab_result))
        self.taxiout_btn_save_result.clicked.connect(lambda: _route_save2file(self.taxiout_tab_result))
        self.taxiout_sig_get_result.connect(lambda data: _table_load_taxi_route(self.taxiout_tab_result, data))

        self.taxiin_route_sig_download_finished.connect(self.taxiin_route_download_data_show)

        self.taxiin_btn_load_from_map.clicked.connect(self.taxiin_route_load_from_map)

    def taxiin_route_load_from_map(self):
        #print('taxiin_route_sig_load_from_map emit')
        self.taxiin_route_sig_load_from_map.emit()

    def taxiin_route_download_data_show(self, taxi_route_list):
        _table_load_taxi_route(self.taxiin_tab_editing, taxi_route_list)
        #print('_table_load_taxi_route')
        #print(taxi_route_list)

    def show_taxi_route2map(self, tab_route: QTableWidget):
        routelist, dot_num = _check_and_get_taxi_route(tab_route)
        self.taxi_route_sig_show2map.emit(routelist)

    def taxiin_upload(self):
        routelist, dot_num = _check_and_get_taxi_route(self.taxiin_tab_editing)
        self.taxiin_sig_upload_start.emit(routelist, dot_num)

    def taxiout_upload(self):
        routelist, dot_num = _check_and_get_taxi_route(self.taxiout_tab_editing)
        self.taxiout_sig_upload_start.emit(routelist, dot_num)

    def rwy_update_result(self, data):
        try:
            takeoff_rwy = data['takeoff_rwy']
            landing_rwy = data['landing_rwy']
            t_rwy_apt_code = "XXXX"
            t_rwy_id = str(takeoff_rwy["idx"])
            t_rwy_start_lon = str(takeoff_rwy["lon"])
            t_rwy_start_lat = str(takeoff_rwy["lat"])
            t_rwy_alt = str(takeoff_rwy["alt"])
            t_rwy_heading = str(takeoff_rwy["psi"])
            t_rwy_len = str(takeoff_rwy["len"])
            self.tab_output.setItem(0, 0, QTableWidgetItem(t_rwy_apt_code))
            self.tab_output.setItem(0, 1, QTableWidgetItem(t_rwy_id))
            self.tab_output.setItem(0, 2, QTableWidgetItem(t_rwy_start_lon))
            self.tab_output.setItem(0, 3, QTableWidgetItem(t_rwy_start_lat))
            self.tab_output.setItem(0, 4, QTableWidgetItem(t_rwy_heading))
            self.tab_output.setItem(0, 5, QTableWidgetItem(t_rwy_alt))
            self.tab_output.setItem(0, 6, QTableWidgetItem(t_rwy_len))

            t_rwy_apt_code = "XXXX"
            t_rwy_id = str(landing_rwy["idx"])
            t_rwy_start_lon = str(landing_rwy["lon"])
            t_rwy_start_lat = str(landing_rwy["lat"])
            t_rwy_alt = str(landing_rwy["alt"])
            t_rwy_heading = str(landing_rwy["psi"])
            t_rwy_len = str(landing_rwy["len"])
            self.tab_output.setItem(1, 0, QTableWidgetItem(t_rwy_apt_code))
            self.tab_output.setItem(1, 1, QTableWidgetItem(t_rwy_id))
            self.tab_output.setItem(1, 2, QTableWidgetItem(t_rwy_start_lon))
            self.tab_output.setItem(1, 3, QTableWidgetItem(t_rwy_start_lat))
            self.tab_output.setItem(1, 4, QTableWidgetItem(t_rwy_heading))
            self.tab_output.setItem(1, 5, QTableWidgetItem(t_rwy_alt))
            self.tab_output.setItem(1, 6, QTableWidgetItem(t_rwy_len))
        except Exception as err:
            logging.error(repr(err))

    def rwy_get_config(self):
        self.rwy_sig_get_rwy.emit()

    def rwy_sig_del_config_process(self):
        """
        接收到外部返回删除跑道指令成功的消息后清除查询结果
        :return:
        """
        self.rwy_clear_result()

    def rwy_sig_get_config_process(self, data):
        """
        TODO:通过外部传入信号获取到跑道数据，显示在result表格中
        :param data:
        :return:
        """
        pass

    def rwy_delete_config(self):
        self.rwy_sig_delete_rwy.emit()
        self.rwy_clear_result()

    def rwy_show_config2map(self):
        # 计算跑道参数，显示跑道信息到地图中
        map_rwy_data = {
            "start_lon": 0,
            "start_lat": 0,
            "end_lon": 0,
            "end_lat": 0,
            "width": DEFAULT_RWY_WIDTH
        }
        try:
            start_lon = float(self.tab_output.item(0, 2).text().strip())
            start_lat = float(self.tab_output.item(0, 3).text().strip())
            tmp_psi = float(self.tab_output.item(0, 4).text().strip())
            rwy_len = float(self.tab_output.item(0, 6).text().strip())
            map_rwy_data['start_lon'] = start_lon
            map_rwy_data['start_lat'] = start_lat
            map_rwy_data['end_lon'], map_rwy_data['end_lat'] = calc_ref_lonlat(start_lon, start_lat, tmp_psi, rwy_len)
            map_rwy_data['width'] = DEFAULT_RWY_WIDTH
            self.rwy_sig_show_to_map.emit(map_rwy_data)
            # print(map_rwy_data)
            start_lon = float(self.tab_output.item(1, 2).text().strip())
            start_lat = float(self.tab_output.item(1, 3).text().strip())
            tmp_psi = float(self.tab_output.item(1, 4).text().strip())
            rwy_len = float(self.tab_output.item(1, 6).text().strip())
            map_rwy_data['start_lon'] = start_lon
            map_rwy_data['start_lat'] = start_lat
            map_rwy_data['end_lon'], map_rwy_data['end_lat'] = calc_ref_lonlat(start_lon, start_lat, tmp_psi, rwy_len)
            map_rwy_data['width'] = DEFAULT_RWY_WIDTH
            self.rwy2_sig_show_to_map.emit(map_rwy_data)
            # print(map_rwy_data)
        except Exception as e:
            logging.error(repr(e))

    def rwy_clear_result(self):
        self.tab_output.clearContents()

    def rwy_save_result(self):
        current = os.getcwd()
        filename, filetype = QFileDialog.getSaveFileName(self, 'save file', current, "Runway config Files (*.ini)")
        if len(filename) == 0:
            return
        try:
            cf = configparser.ConfigParser()
            cf.add_section(CFG_NODE_TAKEOFF_RWY)
            cf.set(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_APT_CODE, self.tab_output.item(0, 0).text().strip())
            cf.set(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_ID, self.tab_output.item(0, 1).text().strip())
            cf.set(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_START_LON, self.tab_output.item(0, 2).text().strip())
            cf.set(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_START_LAT, self.tab_output.item(0, 3).text().strip())
            cf.set(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_HEADING, self.tab_output.item(0, 4).text().strip())
            cf.set(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_ALT, self.tab_output.item(0, 5).text().strip())
            cf.set(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_LEN, self.tab_output.item(0, 6).text().strip())

            cf.add_section(CFG_NODE_LANDING_RWY)
            cf.set(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_APT_CODE, self.tab_output.item(1, 0).text().strip())
            cf.set(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_ID, self.tab_output.item(1, 1).text().strip())
            cf.set(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_START_LON, self.tab_output.item(1, 2).text().strip())
            cf.set(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_START_LAT, self.tab_output.item(1, 3).text().strip())
            cf.set(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_HEADING, self.tab_output.item(1, 4).text().strip())
            cf.set(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_ALT, self.tab_output.item(1, 5).text().strip())
            cf.set(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_LEN, self.tab_output.item(1, 6).text().strip())

            cf.write(open(filename, "w"))
        except Exception as e:
            logging.error(repr(e))
            QMessageBox.information(self, "警告", "配置文件保存失败！",
                                    QMessageBox.Yes, QMessageBox.Yes)

    def rwy_clear_input(self):
        # self.tab_input.setItem(0,0,QTableWidgetItem())
        self.tab_input.clearContents()

    def rwy_show2map(self):
        # 计算跑道参数，显示跑道信息到地图中
        map_rwy_data = {
            "start_lon": 0,
            "start_lat": 0,
            "end_lon": 0,
            "end_lat": 0,
            "width": DEFAULT_RWY_WIDTH
        }
        try:
            start_lon = float(self.tab_input.item(0, 2).text().strip())
            start_lat = float(self.tab_input.item(0, 3).text().strip())
            tmp_psi = float(self.tab_input.item(0, 4).text().strip())
            rwy_len = float(self.tab_input.item(0, 6).text().strip())
            map_rwy_data['start_lon'] = start_lon
            map_rwy_data['start_lat'] = start_lat
            map_rwy_data['end_lon'], map_rwy_data['end_lat'] = calc_ref_lonlat(start_lon, start_lat, tmp_psi, rwy_len)
            map_rwy_data['width'] = DEFAULT_RWY_WIDTH
            self.rwy_sig_show_to_map.emit(map_rwy_data)
            # print(map_rwy_data)
            start_lon = float(self.tab_input.item(1, 2).text().strip())
            start_lat = float(self.tab_input.item(1, 3).text().strip())
            tmp_psi = float(self.tab_input.item(1, 4).text().strip())
            rwy_len = float(self.tab_input.item(1, 6).text().strip())
            map_rwy_data['start_lon'] = start_lon
            map_rwy_data['start_lat'] = start_lat
            map_rwy_data['end_lon'], map_rwy_data['end_lat'] = calc_ref_lonlat(start_lon, start_lat, tmp_psi, rwy_len)
            map_rwy_data['width'] = DEFAULT_RWY_WIDTH
            self.rwy2_sig_show_to_map.emit(map_rwy_data)
            # print(map_rwy_data)
        except Exception as e:
            logging.error(repr(e))

    def rwy_upload_landing(self):
        fcc_rwy_data = {
            "idx": 0,
            "lon": 0,
            "lat": 0,
            "alt": 0,
            "psi": 0,
            "len": 0
        }
        try:
            # apt_code = self.tab_input.item(0, 0).text().strip()
            fcc_rwy_data['idx'] = int(self.tab_input.item(1, 1).text().strip())
            fcc_rwy_data['lon'] = float(self.tab_input.item(1, 2).text().strip())
            fcc_rwy_data['lat'] = float(self.tab_input.item(1, 3).text().strip())
            fcc_rwy_data['psi'] = float(self.tab_input.item(1, 4).text().strip())
            fcc_rwy_data['alt'] = float(self.tab_input.item(1, 5).text().strip())
            fcc_rwy_data['len'] = float(self.tab_input.item(1, 6).text().strip())

            self.rwy_sig_upload_landing_rwy.emit(fcc_rwy_data)
        except Exception as e:
            logging.error(repr(e))

    def rwy_upload_takeoff(self):
        fcc_rwy_data = {
            "idx": 0,
            "lon": 0,
            "lat": 0,
            "alt": 0,
            "psi": 0,
            "len": 0
        }
        try:
            # apt_code = self.tab_input.item(0, 0).text().strip()
            fcc_rwy_data['idx'] = int(self.tab_input.item(0, 1).text().strip())
            fcc_rwy_data['lon'] = float(self.tab_input.item(0, 2).text().strip())
            fcc_rwy_data['lat'] = float(self.tab_input.item(0, 3).text().strip())
            fcc_rwy_data['psi'] = float(self.tab_input.item(0, 4).text().strip())
            fcc_rwy_data['alt'] = float(self.tab_input.item(0, 5).text().strip())
            fcc_rwy_data['len'] = float(self.tab_input.item(0, 6).text().strip())

            # self.rwy_sig_upload_landing_rwy.emit(fcc_rwy_data)
            self.rwy_sig_upload_takeoff_rwy.emit(fcc_rwy_data)
        except Exception as e:
            logging.error(repr(e))

    def rwy_save_cfg(self):
        current = os.getcwd()
        filename, filetype = QFileDialog.getSaveFileName(self, 'save file', current, "Runway config Files (*.ini)")
        if len(filename) == 0:
            return

        try:
            # if os.path.exists(filename):
            #     # 弹窗提示是否覆盖该文件
            #     replay = QMessageBox.information(self, "警告", "文件已存在，是否确认覆盖？",
            #                                      QMessageBox.No |
            #                                      QMessageBox.Yes, QMessageBox.Yes)
            #     if replay == QMessageBox.Yes:
            #         os.remove(filename)
            cf = configparser.ConfigParser()
            cf.add_section(CFG_NODE_TAKEOFF_RWY)
            cf.set(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_APT_CODE, self.tab_input.item(0, 0).text().strip())
            cf.set(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_ID, self.tab_input.item(0, 1).text().strip())
            cf.set(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_START_LON, self.tab_input.item(0, 2).text().strip())
            cf.set(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_START_LAT, self.tab_input.item(0, 3).text().strip())
            cf.set(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_HEADING, self.tab_input.item(0, 4).text().strip())
            cf.set(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_ALT, self.tab_input.item(0, 5).text().strip())
            cf.set(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_LEN, self.tab_input.item(0, 6).text().strip())

            cf.add_section(CFG_NODE_LANDING_RWY)
            cf.set(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_APT_CODE, self.tab_input.item(1, 0).text().strip())
            cf.set(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_ID, self.tab_input.item(1, 1).text().strip())
            cf.set(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_START_LON, self.tab_input.item(1, 2).text().strip())
            cf.set(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_START_LAT, self.tab_input.item(1, 3).text().strip())
            cf.set(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_HEADING, self.tab_input.item(1, 4).text().strip())
            cf.set(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_ALT, self.tab_input.item(1, 5).text().strip())
            cf.set(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_LEN, self.tab_input.item(1, 6).text().strip())

            cf.write(open(filename, "w"))
        except Exception as e:
            logging.error(repr(e))
            QMessageBox.information(self, "警告", "配置文件保存失败！",
                                    QMessageBox.Yes, QMessageBox.Yes)

    def rwy_read_cfg(self):
        current = os.getcwd()
        filename, filetype = QFileDialog.getOpenFileName(self,
                                                         "选取文件",
                                                         current,
                                                         "Runway config Files (*.ini)")
        if len(filename) == 0:
            return

        # print(filename)
        # print(filetype)
        # 读取文件
        if os.path.exists(filename):
            cf = configparser.ConfigParser()
            try:
                cf.read(filename)
                t_rwy_apt_code = cf.get(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_APT_CODE, fallback=None)
                t_rwy_id = cf.get(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_ID, fallback=None)
                t_rwy_start_lon = cf.get(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_START_LON, fallback=None)
                t_rwy_start_lat = cf.get(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_START_LAT, fallback=None)
                t_rwy_end_lon = cf.get(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_END_LON, fallback=None)
                t_rwy_end_lat = cf.get(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_END_LAT, fallback=None)
                t_rwy_heading = cf.get(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_HEADING, fallback=None)
                t_rwy_alt = cf.get(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_ALT, fallback=None)
                t_rwy_len = cf.get(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_LEN, fallback=None)
                t_rwy_width = cf.get(CFG_NODE_TAKEOFF_RWY, CFG_ITEM_RWY_WIDTH, fallback=None)
                # self.tab_input
                self.tab_input.setItem(0, 0, QTableWidgetItem(t_rwy_apt_code))
                self.tab_input.setItem(0, 1, QTableWidgetItem(t_rwy_id))
                self.tab_input.setItem(0, 2, QTableWidgetItem(t_rwy_start_lon))
                self.tab_input.setItem(0, 3, QTableWidgetItem(t_rwy_start_lat))
                self.tab_input.setItem(0, 4, QTableWidgetItem(t_rwy_heading))
                self.tab_input.setItem(0, 5, QTableWidgetItem(t_rwy_alt))
                self.tab_input.setItem(0, 6, QTableWidgetItem(t_rwy_len))

                l_rwy_apt_code = cf.get(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_APT_CODE, fallback=None)
                l_rwy_id = cf.get(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_ID, fallback=None)
                l_rwy_start_lon = cf.get(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_START_LON, fallback=None)
                l_rwy_start_lat = cf.get(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_START_LAT, fallback=None)
                l_rwy_end_lon = cf.get(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_END_LON, fallback=None)
                l_rwy_end_lat = cf.get(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_END_LAT, fallback=None)
                l_rwy_heading = cf.get(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_HEADING, fallback=None)
                l_rwy_alt = cf.get(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_ALT, fallback=None)
                l_rwy_len = cf.get(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_LEN, fallback=None)
                l_rwy_width = cf.get(CFG_NODE_LANDING_RWY, CFG_ITEM_RWY_WIDTH, fallback=None)
                # self.tab_input
                self.tab_input.setItem(1, 0, QTableWidgetItem(l_rwy_apt_code))
                self.tab_input.setItem(1, 1, QTableWidgetItem(l_rwy_id))
                self.tab_input.setItem(1, 2, QTableWidgetItem(l_rwy_start_lon))
                self.tab_input.setItem(1, 3, QTableWidgetItem(l_rwy_start_lat))
                self.tab_input.setItem(1, 4, QTableWidgetItem(l_rwy_heading))
                self.tab_input.setItem(1, 5, QTableWidgetItem(l_rwy_alt))
                self.tab_input.setItem(1, 6, QTableWidgetItem(l_rwy_len))
                # 此处获取的是字符串变量，使用时需要转换为浮点数
            except BaseException as e:
                logging.error(repr(e))


# 地面站软件的入口程序
if __name__ == '__main__':
    # 启动地面站主界面
    app = QtWidgets.QApplication(sys.argv)
    gcs_main_window = QtWidgets.QMainWindow()
    ui = AirportSetPad()
    ui.setupUi(gcs_main_window)
    ui.gui_init()
    gcs_main_window.show()  # 显示窗口

    sys.exit(app.exec_())
